import { Component, OnInit } from '@angular/core';
import { FarmService } from 'app/service/farm.service';
import { DataSourceService } from 'app/service/data-source/data-source.service';
import { ApplicationService } from 'app/service/application.service';
import { DatePipe } from '@angular/common';
import { Farm } from 'app/entity/farm.model';
import { Tag } from 'app/entity/tag.model';
import { LimitedPhotovoltaicLoad } from './limited-photovoltaic-load';
import { TagData } from 'app/entity/tag-data.model';

@Component({
  selector: 'app-photovoltaic-curve',
  templateUrl: './photovoltaic-curve.component.html',
  styleUrls: ['./photovoltaic-curve.component.css']
})
export class PhotovoltaicCurveComponent implements OnInit {

  /**
   * 风场集合
   *
   * @type {Farm[]}
   * @memberof PhotovoltaicCurveComponent
   */
  public farms: Farm[] = [];
  //当前风场
  public currentFarm: LimitedPhotovoltaicLoad;
  farm: Farm;
  farmId: number = 0;
  active: number = null;

  /**
   * 风场负荷模型
   *
   * @type {LimitedFarm[]}
   * @memberof FarmEchartsComponent
   */
    // public limitedPhotovoltaicLoads: LimitedPhotovoltaicLoad[] = [];

  private historyInterval: number = 1 * 600;    //600秒
  private pushInterval: number = /* 10 * 60 */900;      //900秒
  private now: Date = new Date();
  private startTime: Date = new Date(this.now.getFullYear(), this.now.getMonth(), this.now.getDate());
  private endTime: Date = new Date();


  constructor(
    private farmService: FarmService,
    private dataSource: DataSourceService,
    private application: ApplicationService,
    private datePipe: DatePipe,
  ) { }

  ngOnInit() {
    this.farms = this.application.currentUserFarms.filter(farm => farm.farmCategory.startsWith('photovoltaic'));
    this.initData(this.farms[0]);
  }

  ngOnDestroy(): void {
    this.dataSource.dispose();
  }

  private initData(farm: Farm) {

    this.createLimitedFarm(farm);
  }

  private createLimitedFarm(farm: Farm) {
    if (farm != null) {
      let Temperature = this.application.tagDict["ZLSYZYC1177"];//温度
      let Power = this.application.tagDict["ZLSYZYC1093"];//功率
      let Radiation = this.application.tagDict["ZLSYZYC1183"];//辐射
      let Pressure = this.application.tagDict["ZLSYZYC1179"];//气压
      let Precipitation = this.application.tagDict["Precipitation"];//降水
      //初始化数据
      this.currentFarm = new LimitedPhotovoltaicLoad();
      this.currentFarm.farmId= farm.farmId;
      this.currentFarm.farmCode= farm.farmCode;
      this.currentFarm.farmName= farm.farmName;
      //温度
      this.currentFarm.temperatureBinging= this.dataSource.binding([farm.farmCode], Temperature);
      this.currentFarm.temperatures= [];
      this.currentFarm.temperature= [];
      this.currentFarm.yesterdayTemperatures= [];
      //功率
      this.currentFarm.powerBinging= this.dataSource.binding([farm.farmCode], Power);
      this.currentFarm.powers= [];
      this.currentFarm.power= [];
      this.currentFarm.yesterdayPowers= [];
      //辐射
      this.currentFarm.radiationBinging= this.dataSource.binding([farm.farmCode], Radiation);
      this.currentFarm.radiations= [];
      this.currentFarm.radiation=[];
      this.currentFarm.yesterdayRadiations= [];
      //气压
      this.currentFarm.pressureBinging= this.dataSource.binding([farm.farmCode], Pressure);
      this.currentFarm.pressures= [];
      this.currentFarm.pressure= [];
      this.currentFarm.yesterdayPressures= [];
      //降水
      this.currentFarm.precipitationBinging= this.dataSource.binding([farm.farmCode], Precipitation);
      this.currentFarm.precipitations= [];
      this.currentFarm.precipitation= [];
      this.currentFarm.yesterdayPrecipitations= [];

      this.currentFarm.time= new Date();
    }



    //绑定数据
    this.dataSource
      .withHistories(this.startTime, this.endTime, { history: this.historyInterval, push: this.pushInterval })
      .subscribe(
        next => {

          if (next.intervalData) {  //返回当前的数据

            let power = this.currentFarm.powerBinging;
            let temperature = this.currentFarm.temperatureBinging;
            let radiation = this.currentFarm.radiationBinging;
            let pressure = this.currentFarm.pressureBinging;
            let precipitation = this.currentFarm.precipitationBinging;


            this.currentFarm.power = [power.time, power.value.toFixed(2)];
            this.currentFarm.temperature = [temperature.time, temperature.value.toFixed(2)];
            this.currentFarm.radiation = [radiation.time, radiation.value.toFixed(2)];
            this.currentFarm.pressure = [pressure.time, pressure.value.toFixed(2)];
            this.currentFarm.precipitation = [precipitation.time, precipitation.value.toFixed(2)];

          }
          if (next.historyData) {     //返回历史数据
            let powerHistoryData = next.historyData.filter(o => o.code == this.currentFarm.powerBinging.code);
            let powerHistoryTrend: any[] = [];
            powerHistoryData.forEach(tagData => {
              try {
                powerHistoryTrend.push([tagData.time, tagData.value.toFixed(2)]);
              }
              catch (error) {
                console.log(error);
              }
            });
            this.currentFarm.powers = powerHistoryTrend;


            let temperatureHistoryData = next.historyData.filter(o => o.code == this.currentFarm.temperatureBinging.code);
            let temperatureHistoryTrend: any[] = [];
            temperatureHistoryData.forEach(tagData => {
              try {
                temperatureHistoryTrend.push([tagData.time, tagData.value.toFixed(2)]);
              }
              catch (error) {
                console.log(error);
              }
            });
            this.currentFarm.temperatures = temperatureHistoryTrend;


            let radiationHistoryData = next.historyData.filter(o => o.code == this.currentFarm.radiationBinging.code);
            let radiationHistoryTrend: any[] = [];
            radiationHistoryData.forEach(tagData => {
              try {
                radiationHistoryTrend.push([tagData.time, tagData.value.toFixed(2)]);
              }
              catch (error) {
                console.log(error);
              }
            });
            this.currentFarm.radiations = radiationHistoryTrend;


            let pressureHistoryData = next.historyData.filter(o => o.code == this.currentFarm.pressureBinging.code);
            let pressureHistoryTrend: any[] = [];
            pressureHistoryData.forEach(tagData => {
              try {
                pressureHistoryTrend.push([tagData.time, tagData.value.toFixed(2)]);
              }
              catch (error) {
                console.log(error);
              }
            });
            this.currentFarm.pressures = pressureHistoryTrend;


            let precipitationHistoryData = next.historyData.filter(o => o.code == this.currentFarm.precipitationBinging.code);
            let precipitationHistoryTrend: any[] = [];
            precipitationHistoryData.forEach(tagData => {
              try {
                precipitationHistoryTrend.push([tagData.time, tagData.value.toFixed(2)]);
              }
              catch (error) {
                console.log(error);
              }
            });
            this.currentFarm.precipitations = precipitationHistoryTrend;
          }

        },
        error => {
          console.log("FarmLoadTrend subDataStream error", error);
        }
      );
    //加载昨日数据
    let yesterdayCodes: string[] = [];

    yesterdayCodes.push(this.currentFarm.powerBinging.code);
    yesterdayCodes.push(this.currentFarm.temperatureBinging.code);
    yesterdayCodes.push(this.currentFarm.radiationBinging.code);
    yesterdayCodes.push(this.currentFarm.pressureBinging.code);
    yesterdayCodes.push(this.currentFarm.precipitationBinging.code);

    let startTime: Date = new Date(this.now.getFullYear(), this.now.getMonth(), this.now.getDate() - 1);    //前一天0点
    let endTime: Date = new Date(this.now.getFullYear(), this.now.getMonth(), this.now.getDate());         //今天0点

    this.dataSource.history
      .getHistories(yesterdayCodes, startTime, endTime, this.historyInterval)
      .then(res => {
        // if (res.length && res.length > 0)
        this.getYesterday(res, startTime, endTime);
      })
      .catch(error => {
        console.log(error);
      });
  }

  private getYesterday(res: TagData[], startTime: Date, endTime: Date) {
    // this.limitedPhotovoltaicLoads.forEach(farm => {

    let yesterdayPowers: any[] = [];
    let yesterdayTemperatures: any[] = [];
    let yesterdayRadiations: any[] = [];
    let yesterdayPressures: any[] = [];
    let yesterdayPrecipitations: any[] = [];

    let farmYesterdayPowers = res.filter(o => o.code === this.currentFarm.powerBinging.code);
    let farmYesterdayTemperatures = res.filter(o => o.code === this.currentFarm.temperatureBinging.code);
    let farmYesterdayRadiations = res.filter(o => o.code === this.currentFarm.radiationBinging.code);
    let farmYesterdayPressures = res.filter(o => o.code === this.currentFarm.pressureBinging.code);
    let farmYesterdayPrecipitations = res.filter(o => o.code === this.currentFarm.precipitationBinging.code);


    // if (farmYesterdayPowers && farmYesterdayPowers.length) {
    farmYesterdayPowers.forEach(yestPowers => {
      let time: Date = this.parserDate(yestPowers.time)
      yesterdayPowers.push([time, yestPowers.value.toFixed(2)])
    });
    this.currentFarm.yesterdayPowers = yesterdayPowers;
    // };

    // if (farmYesterdayTemperatures && farmYesterdayTemperatures.length) {
    farmYesterdayTemperatures.forEach(yestTemperatures => {
      let time: Date = this.parserDate(yestTemperatures.time)
      yesterdayTemperatures.push([time, yestTemperatures.value.toFixed(2)])
    });
    this.currentFarm.yesterdayTemperatures = yesterdayTemperatures;
    // };

    // if (farmYesterdayRadiations && farmYesterdayRadiations.length) {
    farmYesterdayRadiations.forEach(yestRadiations => {
      let time: Date = this.parserDate(yestRadiations.time)
      yesterdayRadiations.push([time, yestRadiations.value.toFixed(2)])
    });
    this.currentFarm.yesterdayRadiations = yesterdayRadiations;
    // };

    // if (farmYesterdayPressures && farmYesterdayPressures.length) {
    farmYesterdayPressures.forEach(yestPressures => {
      let time: Date = this.parserDate(yestPressures.time)
      yesterdayPressures.push([time, yestPressures.value.toFixed(2)])
    });
    this.currentFarm.yesterdayPressures = yesterdayPressures;
    // };

    // if (farmYesterdayPrecipitations && farmYesterdayPrecipitations.length) {
    farmYesterdayPrecipitations.forEach(yestPrecipitations => {
      let time: Date = this.parserDate(yestPrecipitations.time)
      yesterdayPrecipitations.push([time, yestPrecipitations.value.toFixed(2)])
    });
    this.currentFarm.yesterdayPrecipitations = yesterdayPrecipitations;
    // };
  }

  private parserDate(date) {    //转化为标准日期格式；
    let t = Date.parse(date);
    if (!isNaN(t)) {
      return new Date(Date.parse(date.replace(/-/g, "/")));
    } else {
      return new Date();
    }
  };


  /**
   * 风场选中项变化
   */
  public onChangeFarm(farm: Farm) {
    if (farm != null) {
      this.active = null;
      this.initData(farm);
    }
  }



}


